package com.yangtu.nearbyshop.admin.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangtu.nearbyshop.admin.annotation.RequiresPermissionsDesc;
import com.yangtu.nearbyshop.admin.service.AdminOrderService;
import com.yangtu.nearbyshop.core.notify.NotifyService;
import com.yangtu.nearbyshop.core.notify.NotifyType;
import com.yangtu.nearbyshop.core.util.DateTimeUtil;
import com.yangtu.nearbyshop.core.util.ResponseUtil;
import com.yangtu.nearbyshop.core.validator.Order;
import com.yangtu.nearbyshop.core.validator.Sort;
import com.yangtu.nearbyshop.db.domain.*;
import com.yangtu.nearbyshop.db.service.*;
import com.yangtu.nearbyshop.db.service.itf.*;
import com.yangtu.nearbyshop.db.vo.NearbyshopDispatchVo;
import com.yangtu.nearbyshop.db.vo.NearbyshopPurchaseVo;
import com.yangtu.nearbyshop.db.vo.OrderGoodsVo;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;

import static com.yangtu.nearbyshop.admin.util.AdminResponseCode.LOCK_NO_ORDER;

@RestController
@RequestMapping("/admin/dispatch")
@Validated
public class AdminGoodsOrderController {
    private final Log logger = LogFactory.getLog(AdminGoodsOrderController.class);

    @Autowired
    private AdminOrderService adminOrderService;

    @Autowired
    private NearbyshopOrderService orderService;

    @Autowired
    private NearbyshopOrderGoodsService orderGoodsService;

    @Autowired
    private INearbyshopPurchaseService purchaseService;

    @Autowired
    private INearbyshopDispatchService dispatchService;

    @Autowired
    private INearbyshopOrderService nearbyshopOrderService;

    @Autowired
    private INearbyshopLockService nearbyshopLockService;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private NearbyshopMercService mercService;

    @Autowired
    private NearbyshopUserService userService;

    @Autowired
    private INearbyshopBdMercService bdMercService;

    @Autowired
    private INearbyshopBdService bdService;

    /**
     * @apiDefine dispatch 采购配送接口
     *
     */


    /**
     * 查询订单
     *
     * @param mercNo
     * @param goodId
     * @param startTm
     * @param endTm
     * @param page
     * @param limit
     * @return
     */
    @RequiresPermissions("admin:dispatch:list")
    @RequiresPermissionsDesc(menu = {"采购配送", "采购清单"}, button = "查询")
    @GetMapping("/list")
    public Object list(String mercNo, String goodId, String ordState,
                       String startTm, String endTm,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {
        return adminOrderService.goodsOrderbyGoodsList(mercNo, goodId, ordState, startTm,
                endTm, page, limit);
    }

    /**
     * @api {GET} /admin/dispatch/lock 锁定
     * @apiName dispatch lock
     * @apiGroup dispatch
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     * @apiDescription 将查询结果锁定到采购表中
     *
     * @apiParam {String} [mercNo] 团长NO
     * @apiParam {int} [goodId] 商品id
     * @apiParam {String} ordState 订单状态。201：已付款、其余按原有规定传
     * @apiParam {String} startTm 开始时间
     * @apiParam {String} endTm 结束时间
     * @apiParam {int} [page] 页码
     * @apiParam {int} [limit] 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:dispatch:lock")
    @RequiresPermissionsDesc(menu = {"采购配送", "采购清单"}, button = "锁定")
    @GetMapping("/lock")
    public Object lock(String mercNo, String goodId, String ordState,
                           String startTm, String endTm,
                           @RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer limit) {
        Map<String, Object> map = (Map<String, Object>) adminOrderService.goodsOrderbyGoodsList(mercNo, goodId,
                ordState, startTm, endTm, page, limit);
        Map<String, Object> data = (Map<String, Object>)map.get("data");
        List<Map<String,String>> goodsList = (List<Map<String,String>>)data.get("items");
        if(goodsList.size()==0){
            return ResponseUtil.fail(LOCK_NO_ORDER,"无订单信息");
        }
        List<NearbyshopPurchase> purchases = new ArrayList<>();
        String purNo = "PNO" + System.currentTimeMillis();
        int pnum = 0;
        BigDecimal pprice = new BigDecimal(0);
        Date date = new Date();
        for(Map<String,String> goods : goodsList){
            NearbyshopPurchase purchase = new NearbyshopPurchase();
            purchase.setGoodsId(Integer.valueOf(goods.get("goodsId")));
            purchase.setGoodsName(goods.get("goodsNm"));
            purchase.setGoodsNum(Integer.valueOf(goods.get("goodsNum")));

            purchase.setGoodsSpec(goods.get("specifications"));
            purchase.setOrderStatus(Integer.valueOf(ordState));
            purchase.setPurchaseStatus(0);
            purchase.setCreateTime(date);
            purchase.setStartTime(DateTimeUtil.parseStringToDate(startTm));
            purchase.setEndTime(DateTimeUtil.parseStringToDate(endTm));
            purchase.setPurchaseNo(purNo);
            purchase.setDeleted(0);
            purchases.add(purchase);
        }
        purchaseService.saveBatch(purchases);

        List<Map<String,Object>> orderList = orderService.selectOrderByCond(mercNo,ordState,startTm,endTm);
        List<NearbyshopOrder2> odList = new ArrayList<>();
        for(Map<String,Object> order : orderList){
            NearbyshopOrder2 newOrder = new NearbyshopOrder2();
            String oid = order.get("id").toString();
            newOrder.setId(Integer.valueOf(oid));
            newOrder.setPurchaseNo(purNo);
            newOrder.setPurchaseStatus(0);
            odList.add(newOrder);
        }
        nearbyshopOrderService.updateBatchById(odList);
//        orderService.updateBatch(odList);

        List<Map<String,Object>> disList = orderGoodsService.selectMercOrderByCond(ordState,startTm,endTm);
        List<NearbyshopDispatch> dispatches = new ArrayList<>();
        for(Map<String,Object> order : disList){
            NearbyshopDispatch dispatch = new NearbyshopDispatch();
            dispatch.setCreateTime(date);
            dispatch.setDeleted(0);
            dispatch.setDispatchStatus(0);
            dispatch.setGoodsNum(Integer.valueOf(order.get("goodsNum").toString()));
            pnum += dispatch.getGoodsNum();
            dispatch.setGoodsPrice(new BigDecimal(order.get("goodsPrice").toString()));
            pprice = pprice.add(dispatch.getGoodsPrice());
            dispatch.setMercNo(order.get("mercNo").toString());
            dispatch.setPurchaseNo(purNo);
            dispatch.setPurchaseStatus(0);
            dispatches.add(dispatch);
        }
        dispatchService.saveBatch(dispatches);

        NearbyshopLock lock = new NearbyshopLock();
        lock.setPurchaseNo(purNo);
        lock.setCreateTime(date);
        lock.setDispatchStatus(0);
        lock.setPurchaseStatus(0);
        lock.setStartTime(DateTimeUtil.parseStringToDate(startTm));
        lock.setEndTime(DateTimeUtil.parseStringToDate(endTm));
        lock.setGoodsNum(pnum);
        lock.setGoodsPrice(pprice);
        lock.setLockTime(startTm +"-" + endTm);
        nearbyshopLockService.save(lock);
        return ResponseUtil.ok(purNo);
    }

    /**
     * @api {GET} /admin/dispatch/purchaseOrder 采购单列表
     * @apiName dispatch purchaseOrder
     * @apiGroup dispatch
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} purchaseStatus 0:未采购，1：已采购
     * @apiParam {int} [page] 页码
     * @apiParam {int} [limit] 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "data":  {
     *         "total": 2,
     *         "items": [
     *             {
     *                 "id":1,                              //锁定表id
     *                 "purchaseNo": "PNO1566915998912",   //锁定编号
     *                 "goodsNum": 55,                     //商品总数
     *                 "createTime": "2019-08-27 22:26:39",  //锁定时间
     *                 "startTime": "2019-08-27 22:26:38",   //锁定范围开始时间
     *                 "endTime": "2019-08-27 22:26:39",     //锁定范围结束时间
     *                 "lockTime": "2019-08-27 22:26:39-2019-08-27 22:26:39",     //锁定范围
     *                 "purchaseStatus": 1    //采购状态  1：已采购  0：未采购
     *             }
     *         ]
     *     },
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:dispatch:purchaseOrder")
    @RequiresPermissionsDesc(menu = {"采购配送", "采购清单"}, button = "采购单列表")
    @GetMapping("/purchaseOrder")
    public Object purchaseOrder(Integer purchaseStatus,@RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "10") Integer limit) {
        Page<NearbyshopLock> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        //IPage<NearbyshopPurchaseVo> pList = purchaseService.selectOrderByPage(pageVo,1);
        IPage<NearbyshopLock> pList = nearbyshopLockService.page(pageVo,new QueryWrapper<NearbyshopLock>()
                .eq("purchase_status",purchaseStatus)
                .orderByDesc("create_time"));
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /admin/dispatch/purchaseList 采购单详情
     * @apiName dispatch purchaseList
     * @apiGroup dispatch
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} purchaseNo 锁定编号
     * @apiParam {int} [page] 页码
     * @apiParam {int} [limit] 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "data": {
     *         "total": 20,
     *         "items": [
     *             {
     *                 "id": 1543,
     *                 "purchaseNo": "PNO1566898601003",   //锁定编号
     *                 "goodsId": 1181236,                 //商品id
     *                 "goodsName": "1111111",            //商品名称
     *                 "goodsNum": 1,                     //商品数量
     *                 "goodsSpec": "[\"标准\"]",         //商品规格
     *                 "createTime": "2019-08-27 09:36:41",    //锁定的时间
     *                 "startTime": "2019-08-27 09:36:41",    //锁定开始的时间
     *                 "endTime": "2019-08-27 09:36:41",    //锁定结束的时间
     *                 "orderStatus": 0,                      //订单状态
     *                 "purchaseStatus": 1,                //是否已采购 0：否  1：是
     *                 "deleted": 0
     *             }
     *         ]
     *     },
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:dispatch:purchaseList")
    @RequiresPermissionsDesc(menu = {"采购配送", "采购清单"}, button = "采购单详情")
    @GetMapping("/purchaseList")
    public Object purchaseList(String purchaseNo,@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer limit) {
        Page<NearbyshopPurchase> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<NearbyshopPurchase> pList = purchaseService.selectByPage(pageVo,null,purchaseNo);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /admin/dispatch/purchaseDone 设置已采购
     * @apiName dispatch purchaseDone
     * @apiGroup dispatch
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} purchaseNo 锁定编号
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:dispatch:purchaseDone")
    @RequiresPermissionsDesc(menu = {"采购配送", "采购清单"}, button = "设置已采购")
    @GetMapping("/purchaseDone")
    public Object purchaseDone(String purchaseNo) {
        nearbyshopLockService.updatePurchaseStatus(purchaseNo,1);
        return ResponseUtil.ok(null);
    }

   /*
    @RequiresPermissions("admin:dispatch:list")
    @RequiresPermissionsDesc(menu = {"采购配送", "采购清单"}, button = "已锁定")
    @GetMapping("/lockList")
    public Object lockList(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer limit) {
        Page<NearbyshopPurchase> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<NearbyshopPurchase> pList = purchaseService.selectByPage(pageVo,0,null);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

*/


    /**
     * @api {GET} /admin/dispatch/dispatchOrder 查询配送单信息
     * @apiName dispatch dispatchOrder
     * @apiGroup dispatch
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} dispatchStatus 配送状态 1：已配送   0：未配送
     * @apiParam {int} [page] 页码
     * @apiParam {int} [limit] 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "data": {
     *         "total": 1,
     *         "items": [
     *             {
     *                 "id": 1572,   //配送记录id
     *                 "purchaseNo": "PNO1567158397764",  //锁定编号
     *                 "mercNo": "merc1908141718501891",  //团长编号
     *                 "goodsNum": 78,   //商品总数
     *                 "goodsPrice": "241.06",  //商品总金额
     *                 "createTime": "2019-08-30T09:46:38.000+0000",  //锁定时间
     *                 "dispatchTime": "2019-08-30T09:46:38.000+0000",  //配送时间
     *                 "dispatchStatus": 1,  //配送状态
     *                 "purchaseStatus": 0,  //采购状态
     *                 "mercName": "金升社区E区菜鸟驿站",  //门店名称
     *                 "mercAddr": "山东省临沂市兰山区金升社区e区一号楼27600",  //门店地址
     *                 "username": "王艳",   //联系人
     *                 "mobile": "13405396950",   //联系电话
     *                 "deleted": 0，
     *                 "startTime": "2019-08-30 09:46:38",  //锁定开始时间
     *                 "endTime": "2019-08-30 09:46:38"  //锁定结束时间
     *             }
     *         ]
     *     },
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:dispatch:dispatchOrder")
    @RequiresPermissionsDesc(menu = {"采购配送", "配送清单"}, button = "查询配送单信息")
    @GetMapping("/dispatchOrder")
    public Object dispatchOrder(Integer dispatchStatus,
                           @RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer limit) {
        Page<NearbyshopDispatchVo> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<NearbyshopDispatchVo> pList = dispatchService.getDispatchList(pageVo,
                null,null,dispatchStatus);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /admin/dispatch/dispatchList 查询配送订单列表
     * @apiName dispatch dispatchList
     * @apiGroup dispatch
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} mercNo 团长编号
     * @apiParam {String} purchaseNo 锁定编号
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "data": {
     *         "total": 27,
     *         "items": [
     *             {
     *                 "id": 233,   //订单id
     *                 "userId": 535,   //用户id
     *                 "mercNo": "merc1908141718501891",
     *                 "orderSn": "20190819275237",  //订单编号
     *                 "corgOrderSn": "test",
     *                 "orderStatus": 201,
     *                 "consignee": "郝学森",    //用户名
     *                 "mobile": "13853914448",  //用户电话
     *                 "address": "",
     *                 "message": "",
     *                 "goodsPrice": 11.99,
     *                 "freightPrice": 0.00,
     *                 "couponPrice": 0.00,
     *                 "integralPrice": 0.00,
     *                 "grouponPrice": 0.00,
     *                 "orderPrice": 11.99,
     *                 "actualPrice": 11.99,  //实付金额
     *                 "payId": "4200000352201908195222158107",
     *                 "payTime": "2019-08-19 14:52:07",
     *                 "comments": 0,
     *                 "addTime": "2019-08-19 14:51:56",
     *                 "updateTime": "2019-08-19 14:52:07",
     *                 "deleted": 0,
     *                 "purchaseNo": "PNO1567158397764",
     *                 "purchaseStatus": 0,   //采购状态
     *                 "dispatchStatus": 1,   //配送状态
     *                 "goodsVoList": [],
     *                 "goodsNum": 8,    //商品总数
     *                 "goodsDesc": "1.新鲜水洗胡萝卜【约500g/份】 {标准}(1) (1181186) 2.滕州黄心土豆【约500g/份】 {标准}(6) (1181183) 3.东北西红柿【约1.5kg/份】 {标准}(1) (1181182) "  //商品信息描述
     *             }
     *         ]
     *     },
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:dispatch:dispatchList")
    @RequiresPermissionsDesc(menu = {"采购配送", "配送清单"}, button = "查询配送单列表")
    @GetMapping("/dispatchList")
    public Object dispatchList(String mercNo, String purchaseNo,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "10") Integer limit) {
        Page<NearbyshopOrder2> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(limit);
        IPage<NearbyshopOrder2> pList = nearbyshopOrderService
                .page(pageVo,new QueryWrapper<NearbyshopOrder2>()
                        .eq("merc_no",mercNo)
                        .eq("purchase_no",purchaseNo));
        List<NearbyshopOrder2> odList = pList.getRecords();
        for(NearbyshopOrder2 od2 : odList){
            List<NearbyshopOrderGoods> goodsList = orderGoodsService.queryByOid(od2.getId());
            int num = 0;
            int i = 1;
            String goodsDesc = "";
            List<OrderGoodsVo> goodsVos = new ArrayList<>();
            for(NearbyshopOrderGoods og : goodsList){
                OrderGoodsVo vo = new OrderGoodsVo();
                vo.setGoodsId(og.getGoodsId());
                vo.setGoodsName(og.getGoodsName());
                vo.setNumber(Integer.valueOf(og.getNumber()));
                vo.setProductId(og.getProductId());
                vo.setSpecifications(og.getSpecifications());
                goodsVos.add(vo);
                num += og.getNumber();
                goodsDesc += i + "."+og.getGoodsName() + " " + ArrayUtils.toString(og.getSpecifications(),",")+
                        " (" + og.getNumber() + ") (" + og.getGoodsId() + ") ";
                i++;
            }
            od2.setGoodsDesc(goodsDesc);
            od2.setGoodsNum(num);
        }
        NearbyshopBdMerc bdMerc = bdMercService.getOne(new QueryWrapper<NearbyshopBdMerc>()
                .eq("merc_no",mercNo));
        NearbyshopBd bd = null;
        if(bdMerc != null){
            bd = bdService.getOne(new QueryWrapper<NearbyshopBd>()
                    .eq("bd_no",bdMerc.getBdNo()));
        }
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", odList);
        data.put("bdInfo", bd);
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /admin/dispatch/dispatchListAll 查询所有配送订单列表
     * @apiName dispatch dispatchListAll
     * @apiGroup dispatch
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} dispatchStatus 配送状态 1：已配送   0：未配送
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "errno": 0,
     *     "data": {
     *         "total": 27,
     *         "items": [
     *             {
     *                      "id": 1572,   //配送记录id
     *                      "purchaseNo": "PNO1567158397764",  //锁定编号
     *                      "mercNo": "merc1908141718501891",  //团长编号
     *                      "goodsNum": 78,   //商品总数
     *                      "goodsPrice": "241.06",  //商品总金额
     *                     "createTime": "2019-08-30T09:46:38.000+0000",  //锁定时间
     *                      "dispatchTime": "2019-08-30T09:46:38.000+0000",  //配送时间
     *                      "dispatchStatus": 1,  //配送状态
     *                      "purchaseStatus": 0,  //采购状态
     *                      "mercName": "金升社区E区菜鸟驿站",  //门店名称
     *                      "mercAddr": "山东省临沂市兰山区金升社区e区一号楼27600",  //门店地址
     *                      "username": "王艳",   //联系人
     *                      "mobile": "13405396950",   //联系电话
     *                      "deleted": 0，
     *                      "startTime": "2019-08-30 09:46:38",  //锁定开始时间
     *                      "endTime": "2019-08-30 09:46:38"  //锁定结束时间
     *                       "bdName":xxx,
     *                       "bdPhone":xxxxx,
     *                       "orderList":[
     *                            {
                  *                 "id": 233,   //订单id
                  *                 "userId": 535,   //用户id
                  *                 "mercNo": "merc1908141718501891",
                  *                 "orderSn": "20190819275237",  //订单编号
                  *                 "corgOrderSn": "test",
                  *                 "orderStatus": 201,
                  *                 "consignee": "郝学森",    //用户名
                  *                 "mobile": "13853914448",  //用户电话
                  *                 "address": "",
                  *                 "message": "",
                  *                 "goodsPrice": 11.99,
                  *                 "freightPrice": 0.00,
                  *                 "couponPrice": 0.00,
                  *                 "integralPrice": 0.00,
                  *                 "grouponPrice": 0.00,
                  *                 "orderPrice": 11.99,
                  *                 "actualPrice": 11.99,  //实付金额
                  *                 "payId": "4200000352201908195222158107",
                  *                 "payTime": "2019-08-19 14:52:07",
                  *                 "comments": 0,
                  *                 "addTime": "2019-08-19 14:51:56",
                  *                 "updateTime": "2019-08-19 14:52:07",
                  *                 "deleted": 0,
                  *                 "purchaseNo": "PNO1567158397764",
                  *                 "purchaseStatus": 0,   //采购状态
                  *                 "dispatchStatus": 1,   //配送状态
                  *                 "goodsVoList": [],
                  *                 "goodsNum": 8,    //商品总数
                  *                 "goodsDesc": "1.新鲜水洗胡萝卜【约500g/份】 {标准}(1) (1181186) 2.滕州黄心土豆【约500g/份】 {标准}(6) (1181183) 3.东北西红柿【约1.5kg/份】 {标准}(1) (1181182) "  //商品信息描述
                  *             }
     *                         ]
     *                   }
     *
     *         ]
     *     },
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:dispatch:dispatchListAll")
    @RequiresPermissionsDesc(menu = {"采购配送", "配送清单"}, button = "查询所有配送单列表")
    @GetMapping("/dispatchListAll")
    public Object dispatchListAll(Integer dispatchStatus) {
        Page<NearbyshopDispatchVo> pageVo = new Page<>();
        pageVo.setCurrent(1);
        pageVo.setSize(10000);
        IPage<NearbyshopDispatchVo> dList = dispatchService.getDispatchList(pageVo,
                null,null,dispatchStatus);
        for(NearbyshopDispatchVo nearbyshopDispatchVo : dList.getRecords()){
            List<NearbyshopOrder2> pList = nearbyshopOrderService
                    .list(new QueryWrapper<NearbyshopOrder2>()
                            .eq("merc_no",nearbyshopDispatchVo.getMercNo())
                            .eq("purchase_no",nearbyshopDispatchVo.getPurchaseNo()));
            for(NearbyshopOrder2 od2 : pList){
                List<NearbyshopOrderGoods> goodsList = orderGoodsService.queryByOid(od2.getId());
                int num = 0;
                int i = 1;
                String goodsDesc = "";
                List<OrderGoodsVo> goodsVos = new ArrayList<>();
                for(NearbyshopOrderGoods og : goodsList){
                    OrderGoodsVo vo = new OrderGoodsVo();
                    vo.setGoodsId(og.getGoodsId());
                    vo.setGoodsName(og.getGoodsName());
                    vo.setNumber(Integer.valueOf(og.getNumber()));
                    vo.setProductId(og.getProductId());
                    vo.setSpecifications(og.getSpecifications());
                    goodsVos.add(vo);
                    num += og.getNumber();
                    goodsDesc += i + "."+og.getGoodsName() + " " + ArrayUtils.toString(og.getSpecifications(),",")+
                            " (" + og.getNumber() + ") (" + og.getGoodsId() + ") ";
                    i++;
                }
                od2.setGoodsDesc(goodsDesc);
                od2.setGoodsNum(num);
            }
            nearbyshopDispatchVo.setOrderList(pList);
            NearbyshopBdMerc bdMerc = bdMercService.getOne(new QueryWrapper<NearbyshopBdMerc>()
                    .eq("merc_no",nearbyshopDispatchVo.getMercNo()));
            NearbyshopBd bd = null;
            if(bdMerc != null){
                bd = bdService.getOne(new QueryWrapper<NearbyshopBd>()
                        .eq("bd_no",bdMerc.getBdNo()));
                if(bd != null){
                    nearbyshopDispatchVo.setBdName(bd.getBdName());
                    nearbyshopDispatchVo.setBdPhone(bd.getBdPhone());
                }
            }
        }

        Map<String, Object> data = new HashMap<>();
        data.put("total", dList.getTotal());
        data.put("items", dList.getRecords());
        return ResponseUtil.ok(data);
    }


    /**
     * @api {GET} /admin/dispatch/dispatchDone 设置为已经配送
     * @apiName dispatch dispatchDone
     * @apiGroup dispatch
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 配送id
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:dispatch:dispatchDone")
    @RequiresPermissionsDesc(menu = {"采购配送", "配送清单"}, button = "设置已配送")
    @GetMapping("/dispatchDone")
    public Object dispatchDone(Integer id) {
        dispatchService.updateDispatchDone(id);

        NearbyshopDispatch nearbyshopDispatch = dispatchService.getById(id);
        List<NearbyshopOrder2> ords = nearbyshopOrderService.list(new QueryWrapper<NearbyshopOrder2>()
                .eq("merc_no",nearbyshopDispatch.getMercNo())
                .eq("purchase_no",nearbyshopDispatch.getPurchaseNo()));

        NearbyshopMerc mercInf = mercService.queryByMercNo(nearbyshopDispatch.getMercNo());
        for(NearbyshopOrder2 order:ords){
            //TODO 发送邮件和短信通知，这里采用异步发送
            // 订单支付成功以后，会发送短信给用户，以及发送邮件给管理员
//            notifyService.notifyMail("新订单通知", order.toString());
            // 这里微信的短信平台对参数长度有限制，所以将订单号只截取后6位
//            notifyService.notifySmsTemplateSync(order.getMobile(), NotifyType.SHIP, new String[]{order.getOrderSn().substring(8, 14)});

            NearbyshopUser user = userService.findById(order.getUserId());
            // 请依据自己的模版消息配置更改参数
            String[] parms = new String[]{
                    mercInf.getMercName(),
                    user.getNickname(),
                    order.getOrderSn(),
                   /* order.getOrderPrice().toString(),
                    DateTimeUtil.getDateTimeDisplayString(order.getAddTime()),
                    order.getConsignee(),
                    order.getMobile(),
*/
                    mercInf.getMercAddr()
            };

            notifyService.notifyWxTemplate(user.getWeixinOpenid(),
                    NotifyType.SHIP, parms, "pages/index/index?orderId=" + order.getId());
        }

        return ResponseUtil.ok(null);
    }

    /**
     * @api {GET} /admin/dispatch/orderDetail 用户订单详情
     * @apiName dispatch orderDetail
     * @apiGroup dispatch
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 配送id
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:dispatch:orderDetail")
    @RequiresPermissionsDesc(menu = {"采购配送", "配送清单"}, button = "查询订单详情")
    @GetMapping("/orderDetail")
    public Object orderDetail(Integer id) {
        List<NearbyshopOrderGoods> list = orderGoodsService.queryByOid(id);
        return ResponseUtil.ok(list);
    }




    /**
     * 查询订单
     *
     * @param mercNo
     * @param goodId
     * @param startTm
     * @param endTm
     * @param page
     * @param limit
     * @return
     */
    @RequiresPermissions("admin:dispatch:merclist")
    @RequiresPermissionsDesc(menu = {"采购配送", "配送清单"}, button = "查询")
    @GetMapping("/merclist")
    public Object merclist(String mercNo, String goodId, String ordState,
                       String startTm, String endTm,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {
        return adminOrderService.goodsOrderbyMercList(mercNo, goodId, ordState,
                startTm, endTm, page, limit);
    }

    /**
     * 查询订单
     *
     * @param mercNo
     * @param goodId
     * @param startTm
     * @param endTm
     * @param page
     * @param limit
     * @return
     */
    @RequiresPermissions("admin:dispatch:userlist")
    @RequiresPermissionsDesc(menu = {"采购配送", "用户提货清单"}, button = "查询")
    @GetMapping("/userlist")
    public Object userlist(String mercNo, String goodId, String ordState,
                       String startTm, String endTm,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {

        return adminOrderService.goodsOrderbyUsersList(mercNo, goodId, ordState,
                startTm, endTm, page, limit);
    }

}
